<?php

namespace app\admin\dao;

use app\common\model\AccountBill;
use app\common\model\UserPersonnel;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use ShidianUtil\Utils\TimeUtil;
use think\Collection;

/**
 * UserPersonnelDao 数据访问对象
 * Class UserPersonnelDao
 * @package app\admin\dao
 * @method UserPersonnel findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method UserPersonnel insertActive(array $params, array $allow_field = [])
 * @method UserPersonnel updateActive(UserPersonnel $model, array $params, array $allow_field = [])
 * @method UserPersonnel findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method UserPersonnel updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(UserPersonnel $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class UserPersonnelDao
{
    use DaoTrait;

    /**
     * @var UserPersonnel
     */
    private $baseModel;

    /**
     * UserPersonnelDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = UserPersonnel::class;
    }

    /**
     * 员工列表
     * @param $companyId
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function listPersonnels($companyId, ?int $page, ?int $page_size): array
    {
        $tableName = UserPersonnel::getTable();

        $cardTotalSumSql = AccountBill::whereRaw("proxyUserPersonnelId=$tableName.id")
            ->whereRaw("fromMemberId=$tableName.companyId")
            ->where('fromType', 'company')
            ->where('accountType', 'card')
            ->fieldRaw('sum(`money`)')
            ->buildSql();

        $cardTodaySumSql = AccountBill::whereRaw("proxyUserPersonnelId=$tableName.id")
            ->whereRaw("fromMemberId=$tableName.companyId")
            ->where('fromType', 'company')
            ->where('accountType', 'card')
            ->where('created', '>=', TimeUtil::stamp(TimeUtil::DAY))
            ->fieldRaw('sum(`money`)')
            ->buildSql();

        $coinTotalSumSql = AccountBill::whereRaw("proxyUserPersonnelId=$tableName.id")
            ->whereRaw("fromMemberId=$tableName.companyId")
            ->where('fromType', 'company')
            ->where('accountType', 'coin')
            ->fieldRaw('sum(`money`)')
            ->buildSql();

        $coinTodaySumSql = AccountBill::whereRaw("proxyUserPersonnelId=$tableName.id")
            ->whereRaw("fromMemberId=$tableName.companyId")
            ->where('fromType', 'company')
            ->where('accountType', 'coin')
            ->where('created', '>=', TimeUtil::stamp(TimeUtil::DAY))
            ->fieldRaw('sum(`money`)')
            ->buildSql();

        $query = UserPersonnel::when(is_id($companyId), fn($query) => $query->where('companyId', $companyId))
            ->field(true)
            ->field([
                $cardTotalSumSql => 'cardTotalSum',
                $cardTodaySumSql => 'cardTodaySum',
                $coinTotalSumSql => 'coinTotalSum',
                $coinTodaySumSql => 'coinTodaySum',
            ])
            ->with([
                'company' => fn($query) => $query->field(['id', 'name']),
                'member' => fn($query) => $query->field(['id', 'userPersonnelId']),
                'mobileMember' => fn($query) => $query->field(['id', 'phone', 'userPersonnelId']),
            ])
            ->withAttr([
                'cardTotalSum' => fn($value) => $value ?: 0,
                'cardTodaySum' => fn($value) => $value ?: 0,
                'coinTotalSum' => fn($value) => $value ?: 0,
                'coinTodaySum' => fn($value) => $value ?: 0,
                'inviteUrl' => fn($value, $data) => 'm.xiongmaolvshi.cn/yg/' . $data['id'],
            ])
            ->append(['inviteUrl'])
            ->order('id', 'DESC')
            ->paging($page, $page_size);

        $data = listOutput($query, $page_size);

        // 统计 获客卡 & 通信币使用 & 当日消耗
        $this->wrapPersonnels($data['list']);

        return $data;
    }

    private function wrapPersonnels(Collection $collection)
    {
        $collection->each(function (UserPersonnel $userPersonnel) {
            $userPersonnel->bound = is_null($userPersonnel->member) ? 0 : 1;
            // 是否可以直接登录绑定
            $loginBind = 0;
            if(is_null($userPersonnel->member) && is_null($userPersonnel->mobileMember)){
                $loginBind = 1;
            }
            $userPersonnel->loginBind = $loginBind;
        });
    }
}
